<script setup>
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import titleHeader from '@/components/common/titleHeader.vue'
import { addRule } from '@/utils/Home/user/userRules'
import { roleAddOptions } from '@/utils/role/roleAdd'
import arraysAreEqual from '@/utils/common/arraysAreEqual'
const route = useRoute()

function initRoleAddOptions(arr) {
  let newArr = []
  arr.forEach((item) => {
    if (item.children) {
      item.children.forEach((child) => {
        if (child.children) {
          child.children.forEach((grandson) => {
            newArr.push([item.value, child.value, grandson.value])
          })
        } else {
          newArr.push([item.value, child.value])
        }
      })
    } else {
      newArr.push([item.value])
    }
  })

  return newArr
}
let queryData = {}
function initRoute() {
  if (route.query && route.query.data) {
    try {
      queryData = JSON.parse(route.query.data)
    } catch (error) {
      console.error('Error parsing query data:', error)
    }
  }
}
initRoute()
const props = { multiple: true}

const form = ref({
  // 用户名称
  nickName: queryData.nickName || '',
  //状态
  status: queryData.status || '',
  //菜单权限
  menuPermission: [],
  //楼宇权限
  buildingAuthority: [],
  //角色描述
  remark: ''
})
const options = [
  {
    label: '启用',
    value: '启用'
  },
  {
    label: '禁用',
    value: '禁用'
  }
]
const optionsSex = [
  {
    label: '男',
    value: '男'
  },
  {
    label: '女',
    value: '女'
  }
]
const formRef = ref(null)
const menuPermissionRef = ref(null)
async function handleSave() {
  await formRef.value.validate((valid) => {
    if (!valid) return
    // 成功提交---准备接口
    console.log(form.value)
  })
}

function handleReset() {
  formRef.value.resetFields()
}

const isSeleceAll = ref(false)
const selectItems = ['国际公寓G1', '国际公寓G2', '国际公寓G3', '国际公寓G4']
function handleCheckAllChange(val) {
  form.value.buildingAuthority = val ? selectItems : []
}
function handleChange(val) {
  console.log(val)
  isSeleceAll.value = val.length == selectItems.length ? true : false
}

const isCascaderSeleceAll = ref(false)
function handleCascaderCheckAllChange(e) {
  form.value.menuPermission = e ? initRoleAddOptions(roleAddOptions) : []
}
function handleCascaderChange(val) {
  arraysAreEqual(val, initRoleAddOptions(roleAddOptions))
    ? (isCascaderSeleceAll.value = true)
    : (isCascaderSeleceAll.value = false)
}

const isCollposed = ref(false)
function handleCollposeChange(val) {
  if (val&&form.value.menuPermission.length ==0) {
    form.value.menuPermission =
      form.value.menuPermission.length ==0 ? initRoleAddOptions(roleAddOptions)[0] : []
  }else if (arraysAreEqual(form.value.menuPermission,initRoleAddOptions(roleAddOptions)[0])) {
    form.value.menuPermission=[]
  }
    
}

function handleExpandChange(e) {
  console.log(123)
}
</script>

<template>
  <div class="roleAdd">
    <titleHeader></titleHeader>
    <div class="roleAdd-wrapper">
      <el-form
        :model="form"
        ref="formRef"
        class="form"
        :label-width="95"
        label-position="left"
        :rules="addRule"
      >
        <el-form-item label="角色名称：" prop="nickName" style="width: 300px">
          <el-input v-model.trim="form.nickName"></el-input>
        </el-form-item>
        <el-form-item label="状态：" prop="status" style="width: 300px">
          <el-select v-model.trim="form.status" placeholder="请选择状态">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单权限：" prop="menuPermission">
          <el-checkbox
            v-model="isCollposed"
            @change="handleCollposeChange"
            style="padding-left: 10px"
            >展开/折叠</el-checkbox
          >
          <el-checkbox
            v-model="isCascaderSeleceAll"
            @change="handleCascaderCheckAllChange"
            style="padding-left: 10px"
            >全选/不选</el-checkbox
          >
          <div class="seleceArea" style="padding: 0">
            <el-cascader-panel
              ref="menuPermissionRef"
              v-model="form.menuPermission"
              style="width: fit-content; padding: 0"
              :options="roleAddOptions"
              :props="props"
              @change="handleCascaderChange"
              @expand-change="handleExpandChange"
            />
          </div>
        </el-form-item>
        <el-form-item label="楼宇权限：" prop="buildingAuthority">
          <el-checkbox
            v-model="isSeleceAll"
            @change="handleCheckAllChange"
            style="padding-left: 10px"
            >全选/不选</el-checkbox
          >
          <div class="seleceArea">
            <el-checkbox-group v-model="form.buildingAuthority" @change="handleChange">
              <el-checkbox
                v-for="(item, index) in selectItems"
                :key="index"
                :value="item"
                style="width: 80%"
                >{{ item }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input
            v-model.trim="form.remark"
            style="width: 500px"
            :rows="2"
            :autosize="{ minRows: 4, maxRows: 10 }"
            type="textarea"
            placeholder="请输入角色描述"
          />
        </el-form-item>
      </el-form>
      <div class="form-bottom">
        <el-button type="primary" style="margin: 10px 25px" @click="handleSave">保存</el-button>
        <el-button type="primary" style="margin: 10px 25px" @click="handleReset">取消</el-button>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.roleAdd {
  display: flex;
  flex-direction: column;
  .roleAdd-wrapper {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    padding-top: 10px;
    overflow: hidden;
    .form {
      width: 560px;
      text-align: left;
      .seleceArea {
        min-width: 100%;
        min-height: 100px;
        border: 1px solid #ccc;
        padding: 5px 10px;
      }
    }
    .form-bottom {
      width: 560px;
      display: flex;
      justify-content: space-around;
      align-items: center;
    }
  }
}
:deep() {
  .el-cascader-menu,
  .el-cascader-panel.is-bordered {
    border: none;
  }
  .el-cascader-menu {
    min-width: 150px;
  }
}
</style>
